<template>
    <el-card :class="[prefixCls]" shadow="never">
      <div class="flex items-center">
        <span class="text-16px font-700">用户管理</span>
        <div class="flex pl-20px flex-grow"></div>
      </div>
  
      <wd-crud ref="crudRef" :columns="columns" :crud="crud">
      
        <template #reg_device="{ record }">
            <el-text >
                {{ deviceLabelMap[record?.reg_device] || '未知设备' }}
              </el-text>
          </template>

          <template #phone="{ record }">
            <el-text> 
             {{  record?.idcard?.auth_mobile || record?.phone ||'未申请' }}
             </el-text>
          </template>
        <template #name="{ record }">
          <el-text> 
           {{ record?.idcard?.name || '未申请' }}
           </el-text>
        </template>

        <template #apply_time="{ record }">
            <el-text> 
             {{ record?.idcard?.create_time || '未申请' }}
             </el-text>
          </template>

          <template #credit_total="{ record }">
            <el-text type="primary"> 
             {{ record?.wallet?.total_credit || '未申请' }}
             </el-text>
          </template>
        
          <template #apply_status="{ record }">
            <el-tag
              :type="getTagType(record?.apply?.auth_status)"
            >
              {{ getTagText(record?.apply?.auth_status) }}
            </el-tag>
          </template>
      </wd-crud>
    </el-card>
  
  </template>
  
  <script setup>
  import { reactive, ref, computed, nextTick, unref, watch } from "vue";
  import { useDesign } from "@/hooks/web/useDesign";
  import { useI18n } from "@/hooks/web/useI18n";
  import userApi from "@/apis/user";
  import WdCrud from "@cwd/wd-crud";
  import { message } from "@/utils/message";
  import { useForm } from "@/hooks/web/useForm";
  import { useValidator } from "@/hooks/web/useValidator";
  import Qrcode from "@cps/common/Qrcode/index.vue";
  import { useUserStoreWithOut} from "@/store/modules/user";
  
  const userStore = useUserStoreWithOut();
  
  
  const { formRegister, formMethods } = useForm();
  const { setValues, getElFormExpose, getFormData } = formMethods;
  
  const { required, lengthRange } = useValidator();
  const accountVisible = ref(false);
  
  const { t } = useI18n();
  const { getPrefixCls } = useDesign();
  const prefixCls = getPrefixCls("content-wrap");
  
  const qrCodeDialog = ref(false);
  const qrTheme = ref("theme1");
  const currentItem = ref({});
  const qrcodeImg = ref("");
  // 打开二维码弹窗
  const showQr = (item) => {
    currentItem.value = item;
    qrTheme.value = "theme1"; // 默认选中
    qrcodeImg.value = item?.theme1 || "";
    qrCodeDialog.value = true;
  };
  // 弹窗关闭时重置数据
  const resetQrDialog = () => {
    qrCodeDialog.value = false;
    qrTheme.value = "theme1";
    qrcodeImg.value = "";
    currentItem.value = {};
  };
  watch(qrTheme, (newTheme) => {
    if (currentItem.value && currentItem.value[newTheme]) {
      qrcodeImg.value = currentItem.value[newTheme];
    }
  });
  const crudRef = ref(null);
  const deviceLabelMap = {
  android: '安卓',
  ios: '苹果',
};
  const crud = reactive({
    pk: "uid",
    api: userApi.getPageList,
    showIndex: false,
    pageLayout: "fixed",
    operationColumn: false,
    operationColumnWidth: 260,
    formOption: { viewType: "dialog", width: "60%" },
    isExpand: true,
    beforeOpenAdd: () => {
      return true;
    },
    beforeEdit: (params) => {
      delete params.children;
      return true;
    },
  });
  const getTagType = (status) => {
  switch (status) {
    case 10000:
      return 'success'; // 绿色
    case -10000:
      return 'danger'; // 红色
    case undefined:
    case null:
      return 'info'; // 灰色
    default:
      return 'warning'; // 黄色
  }
};

const getTagText = (status) => {
  switch (status) {
    case 10000:
      return '已通过';
    case -10000:
      return '已驳回';
    case undefined:
    case null:
      return '未申请';
    default:
      return '申请中';
  }
};
  const columns = reactive([
    {
      title: "ID",
      dataIndex: "uid",
      addDisplay: false,
      editDisplay: false,
      width: 50,
      hide: true,
    },
  
    {
      title: "设备",
      dataIndex: "reg_device",
      search: true,
      width: 80,
      textAlign: "left",
      formType: "radio",
      dict: {
        data: [
          { label: "安卓", value: 'android' },
          { label: "苹果", value: 'ios' },
        ],
      },
    },
    {
      title: "姓名",
      dataIndex: "name",
      addDisplay: false,
      editDisplay: false,
      width: 150,
    },
    {
      title: "手机号",
      dataIndex: "phone",
      commonRules: [{ required: true, message: "公司名称必填" }],
      width: 150,
    },
    {
      title: "注册时间",
      dataIndex: "create_time",
      width: 220,
    },
    {
      title: "申请时间",
      dataIndex: "apply_time",
      width: 220,
    },
    {
      title: "授信额度",
      dataIndex: "credit_total",
      width: 150,
    },
    {
      title: "申请时间",
      dataIndex: "reg_time",
      width: 150,
      hide:true,
      search: true,
      formType: "date",
      foremat: "YYYY-MM-DD", // 日期格式
      range: true,
    },
    {
      title: "审核状态",
      dataIndex: "apply_status",
      search: true,
      formType: "radio",
      dict: {
        data: [
          { label: "已通过", value: 20 },
          { label: "审核中", value: 10 },
          { label: "未审核", value: 0 },
        ],
      },
      width: 120,
    },
  ]);
  const changeStatus = async (status, id) => {
    const response = await agentApi.changeStatus({ id, status });
    if (response.success) {
      message(response.message, { type: "success" });
    }
  };
  
  const editAccount = async (record) => {
    accountVisible.value = true;
    await nextTick();
    formMethods.setValues({
      account: record.account,
      agent_id: record.agent_id,
      password: "", // 密码默认留空，如非编辑可省略
    });
  };
  const closeAccount = () => {
    accountVisible.value = false;
  };
  //账号信息修改
  const formSubmit = async () => {
    const accountForm = await formMethods.getElFormExpose();
    if (!accountForm) return;
  
    try {
      await accountForm.validate();
  
      // ✅ 获取表单字段内容
      const formData = await formMethods.getFormData();
      // ✅ 执行提交请求
      const response = await agentApi.modifyAccountInfo(formData.agent_id, {
        ...formData,
      });
  
      // ✅ 响应处理
      if (response.success) {
        accountVisible.value = false;
        accountForm.resetFields();
        crudRef.value.refresh();
        message(response.message, { type: "success" });
      }
    } catch (err) {
      console.warn("表单校验未通过:", err);
    }
  };
  const formSchema = reactive([
    {
      field: "agent_id",
      label: "登录账号",
      component: "Input",
      hidden: true,
    },
    {
      field: "account",
      label: "登录账号",
      component: "Input",
      formItemProps: {
        rules: [required()],
      },
      colProps: {
        span: 24,
      },
    },
    {
      field: "newPassword",
      label: "新密码",
      component: "InputPassword",
      colProps: {
        span: 24,
      },
      componentProps: {
        strength: true,
      },
    },
    {
      field: "newPassword_confirmation",
      label: "确认新密码",
      component: "InputPassword",
      colProps: {
        span: 24,
      },
      componentProps: {
        strength: true,
      },
    },
  ]);
  
  const rules = reactive({
    account: [required()],
    newPassword: [
      required(),
      {
        asyncValidator: async (_, val, callback) => {
          const formData = await getFormData();
          if (val !== formData.newPassword_confirmation) {
            callback(new Error("新密码与确认新密码不一致"));
          } else {
            callback();
          }
        },
      },
    ],
    newPassword_confirmation: [
      required(),
      {
        asyncValidator: async (_, val, callback) => {
          const formData = await getFormData();
          if (val !== formData.newPassword) {
            callback(new Error("确认新密码与新密码不一致"));
          } else {
            callback();
          }
        },
      },
    ],
  });
  </script>
  <style scoped>
  .code {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .bicode {
    border: 1px solid #eee;
    padding: 10px;
    border-radius: 6px;
    background-color: #fff;
  }
  </style>